﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;

class ServerManager
{
    private static ServerManager _instance;
    public static ServerManager Instance()
    {
        if (_instance == null)
        {
            _instance = new ServerManager();
        }
        return _instance;
    }

    public Dictionary<string, SocketClient> dic = new Dictionary<string, SocketClient>();
    //public static Dictionary<Dictionary<string, SocketClient>, string> players = new Dictionary<Dictionary<string, SocketClient>, string>();
    TcpListener listener;
    string IP = "192.168.11.2";
    int Port = 8500;

    private ServerManager()
    {
        IPAddress address = IPAddress.Parse(IP);
        listener = new TcpListener(address, Port);

        listener.Start();
        Console.WriteLine("开始侦听");

        listener.BeginAcceptTcpClient(OnAccecpt, null);
    }

    //接收客户端连接
    void OnAccecpt(IAsyncResult result)
    {
        TcpClient client = listener.EndAcceptTcpClient(result);
        SocketClient remote = new SocketClient(client);

        //把连接的用户存储起来
        dic.Add(client.Client.RemoteEndPoint.ToString(), remote);

        lock (listener)
        {
            listener.BeginAcceptTcpClient(OnAccecpt, null);
        }
    }


    //广播所有人消息<包含自己>
    public void BroadAll(TcpClient client, int protocal, string msg)
    {
        foreach (KeyValuePair<string, SocketClient> item in dic)
        {
            item.Value.SendMessage(protocal, msg);
        }
    }

    //广播给其他人
    public void BroadOther(TcpClient client, int protocal, string msg)
    {
        foreach (KeyValuePair<string, SocketClient> item in dic)
        {
            if (item.Key != client.Client.RemoteEndPoint.ToString())
            {
                item.Value.SendMessage(protocal, msg);
            }
        }
    }

    //把断开的客户端，移除掉
    public void RemoveClient(string key)
    {
        Console.WriteLine(key + "：断开链接");
        dic.Remove(key);
    }


    public void OnMessage(TcpClient client, int protocol, string msg)
    {
        switch (protocol)
        {
            case Protocol.Login_CMD:
                BroadOther(client, protocol, msg);

                dic[client.Client.RemoteEndPoint.ToString()].SendMessage(Protocol.SelfLogin_CMD, msg);
                break;
            case Protocol.PlayerMove_CMD:
                BroadOther(client, protocol, msg);
                break;
            default:
                break;
        }
    }
}
